core.tree = {};

core.tree.TREE_LEVEL_PADDING = 10;
core.tree.TREE_ITEM_HEIGHT = 20;
core.tree.SCROLLBAR_SIZE = 25;

core.tree.TreeItem = function(config){
    this.init(config);
}

core.extendClass('core.tree.TreeItem', 'core.Box');

core.tree.TreeItem.prototype.init = function(config){
    config.items = [];
    this.xType = 'treeItem';
    this.id = config.id || ('ti'+(core.idInc++));
    this.superCall('init', arguments, config);
    this.icons = config.icons;
    this.icon_cls = config.icon_cls;
    this.text = config.text;
    this.type = config.type || 0;//0 - Folder, 1 - Leaf, 2 - Undefined - Loading required
    this.collapsed = config.collapsed;
    this.children = [];
    this.hidden = config.hidden;
    this.loading = false;
    this.elementHeight = core.tree.TREE_ITEM_HEIGHT;
    var instance = this;

    $(this.div).addClass('tree_item');
    this.elementDiv = core.newDiv(this.div, 'tree_item_element');
    this.childrenDiv = core.newDiv(this.div, 'tree_item_children');
    $(this.elementDiv).click(function(e){
        instance.tree.fire('item_click', e, instance);
        instance.tree.selectElement(instance);
        instance.tree.focus();
        return false;
    });

    $(this.elementDiv).dblclick(function(e){
        instance.tree.selectElement(instance);
        if(instance.type==1){
            var res = instance.fire('dblclick', e);
            core.clearSelection();
            return res;
        }
        instance.collapseExpand();
        core.clearSelection();
        return false;
    });

    $(this.elementDiv).mousedown(function(e){
        instance.fire('mousedown', e);
        return false;
    });

    $(this.elementDiv).mousemove(function(e){
        instance.fire('mousemove', e);
        return false;
    });

    $(this.elementDiv).mouseup(function(e){
        instance.fire('mouseup', e);
        return false;
    });

    $(this.elementDiv).mouseout(function(e){
        instance.fire('mouseout', e);
        return false;
    });

    this.buttonDiv = core.newElement(this.elementDiv, 'img', 'icon tree_item_button');
    $(this.buttonDiv).attr('src', 'res/core/sp.png').click(function(e){
        instance.collapseExpand();
        return false;
    });

    this.contentDiv = core.newElement(this.elementDiv, 'span', 'tree_item_content');
    this.cls = config.cls;
//    $(this.contentDiv).click(function(e){
//        e.preventDefault();
//    }).dblclick(function(e){
//        e.preventDefault();
//    });
//    core.log('Created tree item with id '+this.id, this.text);
};

core.tree.TreeItem.prototype.setParent = function(aParent, aPosition){//TreeItem
    this.parent = aParent;
    this.level = aParent.level+1;
//    if(aParent.tree!=this.tree){
        this.tree = aParent.tree;
    var ch = $(aParent.childrenDiv).children();
    if(aPosition>=ch.length){
        $(this.div).appendTo(aParent.childrenDiv);
    }else{
        $(this.div).insertBefore(ch.get(aPosition));
    }
    
//        if(this.dd){
//            this.enableDragging(this.tree, this, this.contentDiv);
//        }
//    }
};

core.tree.TreeItem.prototype.hide = function(){
    this.superCall('hide', arguments);
//    for(var i = 0; i<this.children.length; i++){
//        var ch = this.children[i];
//        ch.hide();
//    }
    this.refresh();
};

core.tree.TreeItem.prototype.refresh = function(){
    if(this.hidden){

    }else{
        var icns = $.makeArray(this.icons);
        $(this.contentDiv).attr('className', 'tree_item_content '+(this.cls?this.cls: ''));
        $(this.contentDiv).html(core.Box.prototype.imagesToHTML(icns)+
            core.Box.prototype.imagesToHTMLSprite(this.icon_cls)+'&nbsp;'+core.escapeHTML(this.text));
        $(this.elementDiv).height(core.tree.TREE_ITEM_HEIGHT);
        if(this.type==1){
            $(this.buttonDiv).attr('className', 'icon');
        }else{
            if(!this.loading){
                $(this.buttonDiv).attr('className', 'icon tree_icns '+(this.collapsed?'tree_coll':'tree_exp'));
            }else{
                $(this.buttonDiv).attr('className', 'icon tree_icn_load');
            }
//            core.Box.prototype.alignBlock(this.buttonDiv, 0, core.tree.TREE_ITEM_HEIGHT, 'left', 'middle');
        }
//        core.Box.prototype.alignBlock(this.contentDiv, 0, core.tree.TREE_ITEM_HEIGHT, 'left', 'middle', textPadding);
        if(this.collapsed){
            $(this.childrenDiv).hide();
        }else{
            $(this.childrenDiv).show();
        }
        this.tree.fixSelection();
    }
};

core.tree.TreeItem.prototype.resize = function(aX, aY, aWidth, aHeight){
//    var textPadding = 16;
//    if(this.hidden){
//        $(this.contentDiv).hide();
//    }else{
//        var icns = $.makeArray(this.icons);
////        if(this.type!=1)
////            icns.splice(0, 0);//Add left icon here
//        $(this.contentDiv).html(core.Box.prototype.imagesToHTML(icns)+
//            core.Box.prototype.imagesToHTMLSprite(this.icon_cls)+core.escapeHTML(this.text));
//        $(this.elementDiv).height(core.tree.TREE_ITEM_HEIGHT);
//        if(this.type==1){
//            $(this.buttonDiv).hide();
//        }else{
//            $(this.buttonDiv).show();
//            if(!this.loading){
//                $(this.buttonDiv).html(core.Box.prototype.imagesToHTMLSprite(
//                    this.collapsed?'tree_coll':'tree_exp', 'tree_icns'));
//            }else{
//                var im = 'res/core/tree/load.gif';
//                $(this.buttonDiv).html('<img src="'+im+'" class="icon"/>');
//            }
//            core.Box.prototype.alignBlock(this.buttonDiv, aWidth, core.tree.TREE_ITEM_HEIGHT, 'left', 'middle');
//        }
//        core.Box.prototype.alignBlock(this.contentDiv, aWidth, core.tree.TREE_ITEM_HEIGHT, 'left', 'middle', textPadding);
//    }
//    for(var i = 0; i<this.children.length; i++){
//        var ch = this.children[i];
//        if(this.collapsed)
//            ch.hide();
//        else{
//            ch.show();
//            ch.resize(aX, aY, aWidth, core.tree.TREE_ITEM_HEIGHT);
//        }
//    }



//    core.log('resize0: ', aX, aY, aWidth, aHeight);
//    var actualWidth = 0;
//    var leftPadding = core.tree.TREE_LEVEL_PADDING;
//    var topPadding = core.tree.TREE_ITEM_HEIGHT;
//
//    if(this.hidden){
//        $(this.contentDiv).hide();
//        leftPadding = 0;
//        topPadding = 0;
//    }else{
//        var icns = $.makeArray(this.icons);
//        if(this.type!=1)
//            icns.splice(0, 0);//Add left icon here
//        $(this.contentDiv).html(core.Box.prototype.imagesToHTML(icns)+
//            core.Box.prototype.imagesToHTMLSprite(this.icon_cls)+core.escapeHTML(this.text));
//        $(this.elementDiv).height(core.tree.TREE_ITEM_HEIGHT);
//        var textPadding = 16;
//        if(this.type==1){
//            $(this.buttonDiv).hide();
//        }else{
//            $(this.buttonDiv).show();
//            if(!this.loading){
//                $(this.buttonDiv).html(core.Box.prototype.imagesToHTMLSprite(
//                    this.collapsed?'tree_coll':'tree_exp', 'tree_icns'));
////                im = this.collapsed?'res/core/tree/coll1.png':'res/core/tree/exp1.png';
//            }else{
//                var im = 'res/core/tree/load.gif';
//                $(this.buttonDiv).html('<img src="'+im+'" class="icon"/>');
//            }
//            core.Box.prototype.alignBlock(this.buttonDiv, aWidth, core.tree.TREE_ITEM_HEIGHT, 'left', 'middle');
//            textPadding = 16;
//        }
////        $(this.elementDiv).width('100%');
//        core.Box.prototype.alignBlock(this.contentDiv, aWidth, core.tree.TREE_ITEM_HEIGHT, 'left', 'middle', aX+textPadding);
//        actualWidth = textPadding+$(this.contentDiv).width()+textPadding;
//    }
//    for(var i = 0; i<this.children.length; i++){
//        var ch = this.children[i];
//        if(this.collapsed)
//            ch.hide();
//        else{
//            ch.show();
//            ch.resize(aX+leftPadding, aY+topPadding, aWidth-leftPadding, core.tree.TREE_ITEM_HEIGHT);
//            if(leftPadding+ch.width>actualWidth)
//                actualWidth = leftPadding+ch.width;
//            topPadding += ch.height;
//        }
//    }
////    core.log('resize: ', actualWidth, leftPadding, topPadding);
//    this.height = topPadding;
//    this.width = actualWidth;
//    this.superCall('resize', arguments, 0, aY, aWidth, this.hidden?0:core.tree.TREE_ITEM_HEIGHT);
//    $(this.elementDiv).css('margin-left', aX);
}

core.tree.TreeItem.prototype.setText = function(aText, aIcons, aIconCls){
    this.text = aText;
    this.icons = aIcons;
    this.icon_cls = aIconCls;
    this.refresh();
    this.tree.bodyChanged();
};

core.tree.TreeItem.prototype.loadComplete = function(aCollapse){
    this.loading = false;
    this.setCollapsed(aCollapse?true:false, false, true);
    this.refresh();
    this.tree.bodyChanged();
}

core.tree.TreeItem.prototype.setCollapsed = function(aCollapsed, aForceRefresh, aIgnoreLoading){
    if(this.type==1 || this.loading)//Leaf
        return false;
    var refresh = aCollapsed!=this.collapsed;
    this.collapsed = aCollapsed;
    if(refresh)
        this.tree.fire('state_change', null, this);
    if(refresh || aForceRefresh){
        if(!aCollapsed && this.type==2 && !aIgnoreLoading){
            this.loading = true;
            this.clear();
            this.fire('load', null, this);
            this.tree.fire('load', null, this);
        }
        this.refresh();
        this.tree.bodyChanged();
        return true;
    }
    return false;
};

core.tree.TreeItem.prototype.getChildCount = function(){
    if(this.type==1 || this.collapsed)
        return 0;
    return this.children.length;
}

core.tree.TreeItem.prototype.nextSibling = function(){
    if(!this.parent || !this.parent.children)
        return null;
    for(var i = 0; i<this.parent.children.length; i++){
        var ch = this.parent.children[i];
        if(ch==this && i<this.parent.children.length-1){
            return this.parent.children[i+1];
        }
    }
    return this.parent.nextSibling();
};

core.tree.TreeItem.prototype.prevSibling = function(){
    if(!this.parent || !this.parent.children)
        return null;
    for(var i in this.parent.children){
        var ch = this.parent.children[i];
        if(ch==this && i>0)
            return this.parent.children[i-1];
    }
    return null;
};

core.tree.TreeItem.prototype.setPosition = function(aPos){
    if(this.parent && this.parent.children){
        for(var i = 0; i<this.parent.children.length; i++){
            if(this.parent.children[i]==this){
//                core.log('setPosition: '+i+', '+aPos);
                if(i!=aPos){
                    this.parent.children.splice(i, 1);
                    this.parent.children.splice(aPos, 0, this);
//                    if(i<aPos)
//                        aPos--;
                    var ch = $(this.parent.childrenDiv).children();
//                    core.log('change pos, now: '+i+" req: "+aPos+", number: "+ch.length);
                    if(aPos>=ch.length-1){
//                        core.log('Appending');
                        $(this.parent.childrenDiv).append(this.div);
                    }else{
//                        core.log('insert before: '+(aPos>i?aPos+1:aPos));
                        $(this.div).insertBefore(ch.get(aPos>i?aPos+1:aPos));
//                        .before(this.div);
                    }
                }
                return;
            }
        }
    }
}

core.tree.TreeItem.prototype.removeFromParent = function(){
    if(this.parent && this.parent.children){
        for(var i = 0; i<this.parent.children.length; i++){
            if(this.parent.children[i]==this){
                this.parent.children.splice(i, 1);
                return;
            }
        }
    }
    $(this.div).remove();
};

core.tree.TreeItem.prototype.clear = function(){
    for (var i = 0; i < this.children.length; i++) {
        this.children[i].remove(true);
    }
    this.children = [];
}

core.tree.TreeItem.prototype.remove = function(aKeepInChildren){
    for (var i = 0; i < this.children.length; i++) {
        this.children[i].remove(true);
    }
    this.children = [];
    if(this.tree && this.tree.selectedElement==this){
//        this.tree.selectedElement = null;
        this.tree.selectElement();
    }
    this.tree = null;
    $(this.div).remove();
    if(!aKeepInChildren){
        this.removeFromParent();
    }

}

core.tree.TreeItem.prototype.markAsDropTarget = function(aDroppable){
//    core.log('mark as target', this.text);
	this.markedAsDropable = true;
	this.dropableCandidate = aDroppable;
    this.tree.ddElement = this;
    this.tree.ddVisible = true;
    $(this.tree.ddSelector).show();
    this.tree.fixSelection();
};

core.tree.TreeItem.prototype.unmarkAsDropTarget = function(){
//    core.log('unmark as target', this.text);
	this.markedAsDropable = false;
    this.tree.ddElement = null;
    this.tree.ddVisible = false;
    $(this.tree.ddSelector).hide();
};

core.tree.TreeItem.prototype.acceptDraggable = function(aDraggable){
    this.tree.fire('dd_end', {}, aDraggable, this);
}

//core.tree.TreeItem.prototype.markAsDropTarget = function(aDropable){
//    this.superCall('markAsDropTarget', arguments, aDropable);
//    $(this.dropTargetDiv).height(core.tree.TREE_ITEM_HEIGHT);
//}
//
//core.tree.TreeItem.prototype.acceptDraggable = function(aDraggable){
//    aDraggable.removeFromParent();
//    if(this.collapsed)
//        this.setCollapsed(false);
//    this.addChild(aDraggable);
//}
//
//core.tree.TreeItem.prototype.getDropTarget = function(aDraggable, aX, aY){
////    core.log('TreeItem:', this.text, this.bounds.y, aY);
//    if(this.type==1)
//        return null;
//    if(aDraggable.tree==this.tree){
//        var itm = this;
//        do{
//            if(itm==aDraggable)
//                return null;
//            itm = itm.parent;
//        }while(itm);
//    }
//    if(!this.hidden && aY>=this.bounds.y && aY<=this.bounds.y+core.tree.TREE_ITEM_HEIGHT){
//        return this;
//    }else{
//        if(!this.collapsed){
//            for(var i = 0; i<this.children.length; i++){
//                var res = this.children[i].getDropTarget(aDraggable, aX, aY);
//                if(res)
//                    return res;
//            }
//        }
//    }
//    return null;
//};

core.tree.TreeItem.prototype.collapseExpand = function(){
    return this.setCollapsed(!this.collapsed);
};

core.tree.TreeItem.prototype.unselectMe = function(){
    $(this.elementDiv).removeClass('tree_item_element_selected');
}

core.tree.TreeItem.prototype.selectMe = function(){
    $(this.elementDiv).addClass('tree_item_element_selected');
}

//core.tree.TreeItem.prototype.replaceChild = function(aChild, aNewElement){
//    for(var i = 0; i<this.children.length; i++){
//        if(this.children[i]==aChild){
//
//            aNewElement.setParent(this);
//            this.children.splice(i, aNewElement);
//            aChild.remove();
//            this.tree.bodyChanged();
//            return aNewElement;
//        }
//    }
//    return null;
//}
//
core.tree.TreeItem.prototype.addChild = function(aChild){
    for(var i = 0; i<this.children.length; i++){
        if(this.children[i]==aChild){
            return aChild;
        }
    }
    this.children.push(aChild);
    aChild.setParent(this, this.children.length);
    aChild.refresh();
    return aChild;
};

core.tree.TreeItem.prototype.insertChild = function(aChild, aPos){
    for(var i = 0; i<this.children.length; i++){
        if(this.children[i]==aChild){
            return aChild;
        }
    }
//    core.log('insertChild', aChild.text, aPos, this.children.length);
    if(aPos>=this.children.length){
        this.children.push(aChild);
    }else{
        this.children.splice(aPos, 0, aChild);
    }
    aChild.setParent(this, aPos);
    aChild.refresh();
    return aChild;
};

core.tree.TreePanel = function(config){
    this.init(config);
};

core.extendClass('core.tree.TreePanel', 'core.form.UIControl');

core.tree.TreePanel.prototype.getTreeItemPos = function(aItem){
    if(!aItem)
        return {
            x: 0,
            y: 0
        };
    var itemPos = $(aItem.div).offset();
    var treePos = $(this.content).offset();
    return {
        x: itemPos.left-treePos.left+$(this.content).scrollLeft(),
        y: itemPos.top-treePos.top+$(this.content).scrollTop()
    }
}

core.tree.TreePanel.prototype.fixSelection = function(){
    if(this.selectedElement){
        this.selectedElement.y = this.getTreeItemPos(this.selectedElement).y;
        $(this.selector).css('top', this.selectedElement.y).show();
    }
    if(this.ddVisible){
        $(this.ddSelector).css('top', this.getTreeItemPos(this.ddElement).y).show();
    }
}

core.tree.TreePanel.prototype.selectElement = function(aElement, aInternalSelect){
//    this.fire('focus');
    if(aElement && aElement.tree!=this)
        return false;
    if(this.selectedElement==aElement)
        return false;
//    if(this.selectedElement)
//        this.selectedElement.unselectMe();
    this.selectedElement = aElement;
    if(this.selectedElement){
        this.fixSelection();
        this.checkTreeItemVisible(aElement);
    }else{
        $(this.selector).hide();
    }
    this.fire('select', {
        automatic: aInternalSelect || false
    }, this.selectedElement);
    return true;
}

core.tree.TreePanel.prototype.doKeyPress = function(e){
    if(e.which==38){//Top
        if(this.selectedElement){
            var s = this.selectedElement.prevSibling();
            if(!s)
                s = this.selectedElement.parent;
            if(s==this.root)
                s = null;
            if(s)
                this.selectElement(s);
        }
        return false;
    }
    if(e.which==40){//Bottom
        if(this.selectedElement){
            var s = null;
            if(this.selectedElement.getChildCount()>0)
                s = this.selectedElement.children[0];
            if(!s)
                s = this.selectedElement.nextSibling();
            if(s)
                this.selectElement(s);
        }
        return false;
    }
    if(e.which==37){//Left - collapse
        if(this.selectedElement)
            this.selectedElement.setCollapsed(true);
        return false;
    }
    if(e.which==39){//Right expand
        if(this.selectedElement)
            this.selectedElement.setCollapsed(false);
        return false;
    }
	return true;
}
core.tree.TreePanel.prototype.searchTreeItem = function(aTreeItem, id){
    if(aTreeItem.id==id)
        return aTreeItem;
    if(aTreeItem.children){
        for (var i = 0; i < aTreeItem.children.length; i++) {
            var itm = aTreeItem.children[i];
            var res = this.searchTreeItem(itm, id);
            if(res!=null)
                return res;
        }
    }
    return null;
};

core.tree.TreePanel.prototype.getTreeItem = function(id){
    return this.searchTreeItem(this.root, id);
};

core.tree.TreePanel.prototype.bodyChanged = function(){
    this.fire('body_change');
};

core.tree.TreePanel.prototype.init = function(config){
    this.superCall('init', arguments, config);
    this.content = core.newDiv(this.div, 'scroll_wrapper');
    this.selector = core.newDiv(this.content, 'tree_selector');
//#ifdef DESKTOP
    this.ddSelector = core.newDiv(this.content, 'dd_target');
    this.ddVisible = false;
    $(this.ddSelector).height(core.tree.TREE_ITEM_HEIGHT).hide();
    $(this.content).addClass('scrollable');
//#endif
    this.treeDiv = core.newDiv(this.content, 'tree_body');
    this.root = new core.tree.TreeItem({
        type: 0,
        id: '$tree$root$id$',
        hidden: true
    });
    this.root.setParent({
        tree: this,
        childrenDiv: this.treeDiv,
        level: 0,
        parent: this
    }, 0);
    this.root.elementHeight = 0;
    $(this.root.elementDiv).hide();
    $(this.root.childrenDiv).css('margin-left', '0px');
    this.root.parent = this;
    $(this.div).addClass('tree_panel');
    if(config.frame){
        this.frame = config.frame;
        config.frame.setMessageHandler('newTree', this, this.loadTree);
        config.frame.setMessageHandler('treeItemModified', this, this.treeItemModified);
        config.frame.setMessageHandler('treeItemSelected', this, this.treeItemSelected);
        config.frame.setMessageHandler('treeItemRemoved', this, this.treeItemRemoved);
        config.frame.setMessageHandler('treeItemInserted', this, this.treeItemInserted);
        config.frame.setMessageHandler('changeTreeItemState', this, this.changeTreeItemState);
    }

};

core.tree.TreePanel.prototype.makeResize = function(aX, aY, aWidth, aHeight){
    if(this.dirty){
        $(this.content).width(aWidth).height(aHeight);
        this.root.resize(0, 0, aWidth, core.tree.TREE_ITEM_HEIGHT);
        var treeWidth = Math.max($(this.root.childrenDiv).width(), aWidth);
    //#ifdef DESKTOP
        var mh = $(this.root.childrenDiv).outerHeight();
        if(aHeight<mh){
            treeWidth -= 20;
        }
    //#endif
        $(this.selector).width(treeWidth);
        $(this.ddSelector).width(treeWidth);
    }
    this.fixSelection();
};


//#ifdef MOBILE
core.tree.TreePanel.prototype.setWidth = function(aWidth){
	this.width = aWidth;
    this.minHeight = $(this.root.childrenDiv).outerHeight();
//    core.log('HTMLPanel: minHeight: '+this.minHeight);
};
//#endif

//#ifdef DESKTOP
core.tree.TreePanel.prototype.getDropTarget = function(aDraggable, aX, aY){
//    core.log('getDropTarget', aX, aY);
//    var treeItem = this.root.getDropTarget(aDraggable, aX, aY);
//    return treeItem;
    var tree = this;
    var checkItemCoordinates = function(aItem, aX, aY){
        var itemPos = tree.getTreeItemPos(aItem);
//        core.log('checkItemCoordinates aY', aY, 'y', itemPos.y, aItem.text);
        if(itemPos.y<=aY && itemPos.y+$(aItem.div).height()>=aY){
            if(itemPos.y+aItem.elementHeight>=aY){
                return aItem;
            }else{
                if(!aItem.collapsed){
                    for (var i = 0; i < aItem.children.length; i++) {
                        var ch = aItem.children[i];
                        var res = checkItemCoordinates(ch, aX, aY);
                        if(res)
                            return res;
                    }
                }
            }
        }
        return null;
    }
    var checkResult = checkItemCoordinates(this.root, aX, aY+$(this.content).scrollTop());
    if(checkResult){
        if(this.fire('accept_target', {}, aDraggable, checkResult))
//            core.log('Found item '+checkResult.text);
            return checkResult;
    }
    return null;
};
//#endif

core.tree.TreePanel.prototype.checkTreeItemVisible = function(aItem){
    if(!aItem)
        return;
    if($(this.content).scrollTop()+this.height-core.tree.TREE_ITEM_HEIGHT-core.tree.SCROLLBAR_SIZE<aItem.y){
        $(this.content).scrollTop(aItem.y+core.tree.TREE_ITEM_HEIGHT-this.height+core.tree.SCROLLBAR_SIZE);
        return;
    }
    if(aItem.y<$(this.content).scrollTop()){
        $(this.content).scrollTop(aItem.y);
        return;
    }
};

core.tree.TreePanel.prototype.loadTreeItem = function(aData, aTreeItem, aPosition){
    var existing = this.getTreeItem(aData.id);
    if(existing)
        return existing;
    var instance = this;
    var ch = new core.tree.TreeItem({
        text: aData.name,
        cls: aData.cls,
        collapsed: aData.collapsed,
        type: aData.type,
        icons: aData.icon!=''?'res/'+aData.icon:null,
        icon_cls: aData.icon_cls,
        id: aData.id
    });
    ch.data = aData.data || {};
    this.fire('add_item', {}, ch);
    if(!aPosition && aPosition!=0){
        ch = aTreeItem.addChild(ch);
    }else{
        ch = aTreeItem.insertChild(ch, aPosition);
    }
    if(ch.type==1){
        //Subscribe to dblclick
        ch.on('dblclick', function(el, e){
            instance.fire('item_dbl_click', e, el);
            return false;
        })
    }

//    if(!aData.childrenAllowed){
//        //Subscribe to dblclick
//        ch.on('dblclick', function(el){
////            core.log('start application');
//            instance.fire('elementDblClick', null, el);
//            return false;
//        })
//    }
    if(aData.children){
        var arr = $.makeArray(aData.children);
        for (var i = 0; i < arr.length; i++) {
            this.loadTreeItem(arr[i], ch);
        }
    }
    return ch;
}

core.tree.TreePanel.prototype.loadTree = function(aData){
    var arr = $.makeArray(aData.children);
    this.root.clear();
    for (var i = 0; i < arr.length; i++) {
        this.loadTreeItem(arr[i], this.root);
    }
    if(aData.selected){
        var itm = this.getTreeItem(aData.selected.id);
        if(itm)
            this.selectElement(itm, true);
    }
    this.bodyChanged();
};

core.tree.TreePanel.prototype.treeItemSelected = function(aData){
//    core.log('treeItemSelected');
    var itm = null;
    if(aData.selected){
//        core.log('treeItemSelected id = '+aData.selected.id);
        itm = this.getTreeItem(aData.selected.id);
    }
    this.selectElement(itm);
};

core.tree.TreePanel.prototype.loadItems = function(aItem, aData){
    aItem.clear();
    var arr = $.makeArray(aData.items);
    if(!aData.collapsed && arr.length>0){
        for (var i = 0; i < arr.length; i++) {
            this.loadTreeItem(arr[i], aItem);
        }
//                item.loadComplete(false);
//            }else
    }
    aItem.loadComplete(false);

};

core.tree.TreePanel.prototype.treeItemModified = function(aData){
    var item = this.getTreeItem(aData.id);
    if(item){
        item.data = aData.data || {};
        item.cls = aData.cls;
        item.setText(aData.name, aData.icon, aData.icon_cls);
        if(aData.position || aData.position==0){
            item.setPosition(aData.position);
            this.bodyChanged();
        }
    }
};

core.tree.TreePanel.prototype.treeItemRemoved = function(aData){
    var item = this.getTreeItem(aData.id);
    if(item){
        item.remove();
        this.bodyChanged();
    }
    if(aData.selectID){
        var sel = this.getTreeItem(aData.selectID);
        this.selectElement(sel);
    }
};

core.tree.TreePanel.prototype.treeItemInserted = function(aData){
//    core.log('Inserting new item...', aData.parentID, aData.id);
    var item = this.getTreeItem(aData.parentID);
    if(item){
//        core.log('Inserting new item', aData.id, aData.position, aData.name, aData.type);
        this.loadTreeItem(aData, item, aData.position);
        this.bodyChanged();
//        core.log('Inserting finished', aData.position);
    }
};

core.tree.TreePanel.prototype.changeTreeItemState = function(aData){
    var item = this.getTreeItem(aData.id);
    if(item){
        item.setCollapsed(aData.collapsed);
    }
}

core.tree.TreePanel.prototype.reloadTree = function(){
    var instance = this;
//    core.log('reloadTree', this.frame);
    if(this.frame){
        this.frame.sendMessage('getTree', {}, function(aData){
            instance.loadTree(aData);
        }, null, this);
    }
}
